package com.zttek.photosShareProject.modules.web.share;

import com.zttek.photosShareProject.common.base.MyBaseController;
import com.zttek.photosShareProject.common.json.ImageVO;
import com.zttek.photosShareProject.common.utils.ImgCompressUtil;
import com.zttek.photosShareProject.common.utils.OSSClientUtil;
import com.zttek.photosShareProject.modules.model.Image;
import com.zttek.photosShareProject.modules.service.login.IUserService;
import com.zttek.photosShareProject.modules.service.share.IImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 13296 on 2017/8/29.
 */
@RequestMapping("/image")
@Controller
public class ImageController extends MyBaseController {

    @Autowired
    private IImageService imageService;

    @Autowired
    private IUserService userService;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadPhotos(@RequestParam("imgFile") MultipartFile imgFile, @RequestParam("userId") Long userId) throws Exception {
        /*上传多图片*/
        ImageVO imageVO = null;
        if (imgFile != null) {
            if (!imgFile.isEmpty()) {
                String md5 = imageService.getImageMD5Val(imgFile);
                Image dup = imageService.checkMd5(md5), image;
                if (dup == null){
                    OSSClientUtil ossClientUtil = new OSSClientUtil();
                    String msg = ossClientUtil.uploadImg2Oss(imgFile);//上传原图片到阿里云
                    String path = ossClientUtil.getImgUrl(msg).split("[?]")[0];
                    //压缩图片
                    String url = ImgCompressUtil.getCompress(imgFile);
                    String thumbMsg = ossClientUtil.uploadImg2Oss(url);//上传压缩图片到阿里云
                    String thumbPath = ossClientUtil.getImgUrl(thumbMsg).split("[?]")[0];

                    String type = path.substring(path.lastIndexOf(".") + 1);
                    image = imageService.newImage(type, path, thumbPath, userId, md5);
                } else {
                    image = dup;
                }

                imageVO = imageService.image2VO(image, true);
            }
        }
        return renderSuccess(imageVO);
    }

    @RequestMapping(value = "/getImage", method = RequestMethod.POST)
    @ResponseBody
    public Object getImage(@RequestParam("imageId") Long imageId) throws Exception {
        Image image = imageService.selectImageById(imageId);
        ImageVO imageVO = imageService.image2VO(image, true);
        return renderSuccess(imageVO);
    }
}
